import { defineStore } from "pinia";
// import { useProductStore} from "./product";

export const useCartStore = defineStore("cart", {
  state: () => ({
    items: uni.getStorageSync("cart") || [],
  }),

  actions: {
    addItem(item) {
      const current = this.items.find((i) => i.id === item.id);
      console.log("🚀 ~ addItem ~ current:", current)
      if (current) {
        current.quantity += 1;
      } else {
        this.items.push({
            ...item,
            quantity: 1
        });
      }
      this.persistCart();
    },

    deleteItem(item) {
        const currentIndex = this.items.find((i) => i.id === item.id);
      if (currentIndex) {
        currentIndex.quantity -= 1;
      }
      this.persistCart();
      },
    // 删除商品
    removeItem(index) {
      this.items.splice(index, 1);
      this.persistCart();
    },

    // 清空购物车
    clearCart() {
      this.items = [];
      this.persistCart();
    },

    persistCart() {
      uni.setStorageSync("cart", this.items);
    },
  },

  getters: {
    cartTotal: (state, store) => {
      return state.items.reduce(
        (total, item) => {
          total.num += item.quantity;
          total.price += item.price * item.quantity;
          return total;
        },
        { num: 0, price: 0 }
      );
    },
  },
});
